package main

import (
	"context"
	"fmt"
	"github.com/mongodb/mongo-go-driver/bson/primitive"
	"github.com/mongodb/mongo-go-driver/mongo"
	"time"
)

type LogRecord struct {
	JobName string    `bson:"jobName"`
	Cmd     string    `bson:"cmd"`
	Err     string    `bson:"err"`
	Content string    `bson:"content"`
	Time    TimePoint `bson:"time"`
}

type TimePoint struct {
	StartTime int64 `bson:"startTime"`
	EndTime   int64 `bson:"endTime"`
}

func main() {
	var (
		client     *mongo.Client
		err        error
		database   *mongo.Database
		collection *mongo.Collection
		record     *LogRecord
		insertRes  *mongo.InsertOneResult
	)
	if client, err = mongo.Connect(context.TODO(), "mongodb://localhost:27017"); err != nil {
		fmt.Println(err)
		return
	}

	//选择库
	database = client.Database("cron")

	//选择表
	collection = database.Collection("log")

	//插入(bson)
	record = &LogRecord{
		JobName: "job test",
		Cmd:     "echo hello",
		Err:     "",
		Content: "hello",
		Time: TimePoint{
			StartTime: time.Now().Unix(),
			EndTime:   time.Now().Unix() + 20,
		},
	}
	if insertRes, err = collection.InsertOne(context.TODO(), record); err != nil {
		fmt.Println(err)
		return
	}

	ids := insertRes.InsertedID.(primitive.ObjectID)
	fmt.Println("自增id" + ids.Hex())
}
